<template>
  <el-dialog :title="userid ? '编辑分类' : '添加分类'" :visible="isShowDialog" @close="btnCancel">

    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
      <el-form-item label="标题" prop="title">
        <el-input v-model="ruleForm.title" />
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input v-model="ruleForm.desc" />
      </el-form-item>

      <!-- 放置上传图片 -->
      <el-form-item label="照片" prop="image">
        <ImageUpload ref="userInfoPhoto" />
      </el-form-item>

      <el-row type="flex" justify="center">
        <el-button size="small" type="primary" @click="btnOK">确定</el-button>
        <el-button size="small" @click="btnCancel">取消</el-button>
      </el-row>

    </el-form></el-dialog>
</template>

<script>
import { addCategories, editCategories, DetailById } from '@/api/category'
import ImageUpload from './ImageUpload.vue'

export default {
  components: { ImageUpload },
  props: {
    isShowDialog: {
      type: Boolean,
      default: false
    }

  },
  data() {
    return {
      ruleForm: {
        title: '',
        desc: '',
        image: ''
      },
      rules: {
        title: [{ required: true, message: '该项不能为空', trigger: 'blur' }],
        desc: [{ required: true, message: '该项不能为空', trigger: 'blur' }]
      },
      userid: ''
    }
  },
  // computed: {
  //   showText() {
  //     return this.userid ? '编辑分类' : '添加分类'
  //   }
  // },

  methods: {
    async  btnOK() {
    //  校验表单
      await this.$refs.ruleForm.validate()
      console.log(59, this.ruleForm.image)
      const fileList = this.$refs.userInfoPhoto.fileList
      this.ruleForm.image = fileList[0].url

      console.log(59, this.ruleForm)

      //   发送请求
      if (this.userid) {
        await editCategories(this.userid, this.ruleForm)
      } else {
        await addCategories(this.ruleForm)
      }

      //  await editCategories(this.ruleForm)

      //  提示用户
      this.$message.success('操作成功')
      //  关闭弹窗
      this.$emit('update:isShowDialog', false)
      //  更新页面
      this.$emit('close')
      this.$emit('show')

      // this.$parent.CategoryCount()
      // this.$parent.getCategories()

      // this.ruleForm = {}
    },
    async  btnCancel() {
      this.userid = ''
      await this.$refs.ruleForm.resetFields()
      await this.$emit('update:isShowDialog', false)
      this.$refs.userInfoPhoto.fileList = []
    },
    async  DetailById(id) {
      this.userid = id
      const { data } = await DetailById(id)
      console.log(95, data)
      this.ruleForm = data
      this.$refs.userInfoPhoto.fileList = [
        {
          url: this.ruleForm.image
        }
      ]
    }
  }

}
</script>

<style>

</style>
